const { login } = require('../controller/user')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const { set } = require('../db/redis')
const handleUserRouter = (req, res) => {
  const method = req.method //GET POST
  if (method === 'POST' && req.path === '/api/user/login') {
    const { username, password } = req.body
    const result = login(username, password)
    return result.then((row) => {
      if (row.username) {
        // 操作cookie
        // res.setHeader(
        //   'Set-Cookie',
        //   `username=${
        //     row.username
        //   }; path=/;httpOnly;expires=${getCookieExpires()}`
        // )
        req.session.username = row.username
        req.session.realname = row.realname
        // 同步到redis中
        set(req.sessionId, req.session)
        console.log('session', req.session)
        return new SuccessModel({ token: req.sessionId })
      } else {
        return new ErrorModel('登陆失败')
      }
    })
  }
  // 登录验证的测试
  // if (method === 'GET' && req.path === '/api/user/login-test') {
  //   if (req.session.username) {
  //     return Promise.resolve(
  //       new SuccessModel({
  //         username: req.session,
  //       })
  //     )
  //   }

  //   return Promise.resolve(new ErrorModel('尚未登录'))
  // }
}

module.exports = handleUserRouter
